<template>
  <view ref="containerRef" class="chat-input-container">
    <up-card margin="0px" padding="0px" border-radius="0" :border="false" :head-border-bottom="true"
             style="background-color: #f4f5f7">
      <template #body>
        <up-row gutter="10" custom-style="margin-bottom: 5px; padding: 10px 0 0 0px">
          <up-col span="2" offset="0.5">
            <up-icon size="25" name="mic" @click="openOperationPanel('recordingFlag')"></up-icon>
          </up-col>
          <!--  #ifdef  H5 -->
          <up-col span="2.5">
            <up-icon size="25" name="photo" @click="openPhotoAlbumH5"></up-icon>
          </up-col>
          <up-col span="2.5">
            <up-icon size="19" name="/static/images/icon/video.png" @click="openVideoAlbumH5"></up-icon>
          </up-col>
          <!--  #endif -->
          <!--  #ifdef  MP-WEIXIN || MP-TOUTIAO || MP-XHS || APP-PLUS -->
          <up-col span="2">
            <up-icon size="25" name="photo" @click="selectMediaFile"></up-icon>
          </up-col>
          <up-col span="2">
            <up-icon size="25" name="camera" @click="shootMediaFile"></up-icon>
          </up-col>
          <!--  #endif -->
          <up-col span="2.5">
            <up-icon size="23" name="/static/images/icon/face.png" @click="openOperationPanel('phizFlag')"></up-icon>
          </up-col>
          <up-col span="2.5">
            <up-icon size="25" name="plus-circle" @click="openOperationPanel('operationPanelFlag')"></up-icon>
          </up-col>
        </up-row>
        <up-row gutter="10" custom-style="padding: 5px 5px 10px 5px">
          <up-col span="10">
            <up-textarea
              v-model="val"
              class="input"
              height="20"
              maxlength="500"
              auto-height
              confirm-type="发送"
              :show-confirm-bar="false"
              :selection-start="val.length"
              :adjust-position="false"
              :cursor-spacing="60"
              @focus="onInputFocus"
              @blur="onInputBlur"
              @confirm="onSend"
            ></up-textarea>
          </up-col>
          <up-col span="2">
            <up-button
              style="height: 38px;border-radius: 10px"
              type="primary"
              text="发送"
              :hairline="false"
              @click="onSendText"
            ></up-button>
          </up-col>
        </up-row>
      </template>
    </up-card>
    <view v-if="functionBodyFlag" class="functionBody">
      <emoji v-if="functionBodyList.phizFlag" @call-back-add="emojiCallBackAdd" @call-back-del="emojiCallBackDel"></emoji>
      <recording v-if="functionBodyList.recordingFlag"></recording>
      <operation-panel v-if="functionBodyList.operationPanelFlag"></operation-panel>
    </view>
  </view>
</template>

<script setup lang="ts">
import { guid } from 'uview-plus';
import { to } from 'await-to-js';
import operationPanel from './operation-panel.vue';
import recording from './recording.vue';
import emoji from './emoji.vue';

import { ChatMessageVo } from '@/types/IMMessageDTO';
import useUserStore from '@/store/modules/user';
import { captureCover } from '@/utils';

const userStore = useUserStore();

const emits = defineEmits(['sendCallBack', 'setListHeight']);


const val = ref('');
const containerRef = ref(null);


const clearInput = () => {
  val.value = '';
};


//发送文本消息
const onSendText = async () => {
  const message = val.value.trim();
  if (!message) return;
  const data = {
    id: guid(),
    type: 'TEXT',
    content: message,
    sendUserId: userStore.userId,
    sendTime: new Date(),
    sendUserName: userStore.nickName,
    sendUserAvatar: userStore.avatar,
    uploadFlag: false
  };
  emits('sendCallBack', { ...data });
  data.id = null;
  const [err, res] = await to(uni.$u.http.post(`/work/chatGroup/addChatTextMessage`, data));
  if (res) {
    val.value = '';
  }

};
//h5端选择图片
const openPhotoAlbumH5 = async () => {
  const res = await uni.chooseImage({
    count: 6,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'] //从相册选择
  });
  res.tempFiles.forEach(async (file: File) => {
    const imageInfo = await uni.getImageInfo({ src: file.path });
    const data: ChatMessageVo = {
      id: guid(),
      type: 'IMAGE',
      sendUserId: userStore.userId,
      sendTime: new Date(),
      sendUserName: userStore.nickName,
      sendUserAvatar: userStore.avatar,
      mediaFile: file.path,
      mediaFileUpload: file,
      mediaWidth: imageInfo.width,
      mediaHeight: imageInfo.height,
      uploadFlag: false
    };
    emits('sendCallBack', data);
    uploadFile(data);
  });

};
//h5端选择视频
const openVideoAlbumH5 = async () => {
  const res = await uni.chooseVideo({
    count: 6,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'] //从相册选择
  });
  const videoInfo = await uni.getVideoInfo({ src: res.tempFilePath });
  const { base64, file } = await captureCover(res.tempFilePath);

  const data: ChatMessageVo = {
    id: guid(),
    type: 'VIDEO',
    sendUserId: userStore.userId,
    sendTime: new Date(),
    sendUserName: userStore.nickName,
    sendUserAvatar: userStore.avatar,
    mediaFile: res.tempFilePath,
    videoCover: base64,
    videoCoverUpload: file,
    mediaWidth: videoInfo.width,
    mediaHeight: videoInfo.height,
    videoDuration: videoInfo.duration,
    uploadFlag: false
  };
  emits('sendCallBack', data);
  uploadFile(data);
};
//小程序端选择媒体文件
const selectMediaFile = async () => {
  uni.chooseMedia({
    count: 9,
    mediaType: ['image', 'video'],
    sourceType: ['album'],
    success: function(res) {
      res.tempFiles.forEach(async (file) => {
        const videoCover = await captureCover(file.tempFilePath);
        const data: ChatMessageVo = {
          id: guid(),
          type: file.fileType == 'image' ? 'IMAGE' : 'VIDEO',
          sendUserId: userStore.userId,
          sendTime: new Date(),
          sendUserName: userStore.nickName,
          sendUserAvatar: userStore.avatar,
          mediaFile: file.tempFilePath,
          videoCover: videoCover,
          uploadFlag: false
        };
        emits('sendCallBack', data);
        uploadFile(data);

      });

    }
  });
};
//小程序端拍摄1、媒体文件
const shootMediaFile = () => {
  uni.chooseMedia({
    count: 1,
    maxDuration: 30,
    mediaType: ['image', 'video'],
    sourceType: ['camera'],
    camera: 'back',
    success: function(res) {
      console.log(res);
    }
  });
};


const uploadImgUrl = '/work/chatGroup/addChatMediaMessage'; // 上传的媒体文件服务器地址
const uploadFile = (data: ChatMessageVo) => {
  uni.$u.http.upload(uploadImgUrl, {
    filePath: data.mediaFile,
    name: 'mediaFile',
    timeout: 60000,
    formData: {
      mediaType: data.type,
      mediaId: data.id,
      videoCover: data.videoCoverUpload,
      mediaWidth: data.mediaWidth || 0,
      mediaHeight: data.mediaHeight || 0,
      videoDuration: data.videoDuration || 0
    }
  });

};

//表情回调
const emojiCallBackAdd = (phiz: string) => {
  val.value += phiz;
};
const emojiCallBackDel = () => {
  if (val.value.length > 0) {
    val.value = val.value.slice(0, -2);
  }
};

//关闭功能面板
const closeFunctionBody = () => {
  functionBodyFlag.value = false;
};
const functionBodyList = ref({
  recordingFlag: false,
  operationPanelFlag: false,
  phizFlag: false
});
const functionBodyFlag = ref(false);
//打开更多操作面板
const openOperationPanel = (key: string) => {
  functionBodyFlag.value = true;
  let scrollTo = Object.values(functionBodyList.value).every((value) => value === false);
  emits('setListHeight', '42vh', scrollTo);
  for (let key in functionBodyList.value) {
    functionBodyList.value[key] = false;
  }
  functionBodyList.value[key] = true;
};

//输入框鼠标聚焦
const onInputFocus = (e) => {
  // #ifdef H5
  emits('setListHeight', '88vh', true);
  functionBodyFlag.value = false;
  for (let key in functionBodyList.value) {
    functionBodyList.value[key] = false;
  }

  // #endif
};
//输入框鼠标失焦
const onInputBlur = () => {

};

onLoad(() => {
  //#ifdef APP-PLUS || MP-WEIXIN
  // 监听键盘高度变化
  uni.onKeyboardHeightChange(res => {
    if (res.height > 0) {
      const height = functionBodyFlag.value == true ? '42vh' : '88vh';
      functionBodyFlag.value = false;
      emits('setListHeight', height, true);
    }
    if (res.height <= 0 && functionBodyFlag.value == false) {
      emits('setListHeight', '88vh', true);
    }
  });
  //#endif
});
onUnload(() => {
  //#ifdef APP-PLUS || MP-WEIXIN
  // 页面卸载时取消监听
  uni.offKeyboardHeightChange();
  //#endif
});

defineExpose({
  clearInput,
  closeFunctionBody
});
</script>

<style scoped lang="scss">
.chat-input-container {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f4f5f7;
  .functionBody {
    flex: 1;
    background-color: #f4f5f7;
  }
}

.input {
  max-height: 4.5em;
  line-height: 1em;
  overflow-y: auto;
}

</style>
